<template>
  <div class="main-box">
    <div class="login-box">
      <el-form
          lang="en-hans"
          ref="ruleFormRef"
          :model="ruleForm"
          status-icon
          style="width: 100%;"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm">
        <el-form-item>
          <div class="login-title">
            <h1>心机之蛙</h1>
          </div>
        </el-form-item>
        <el-form-item class="username" prop="username">
          <el-input lang="en-hans" v-model="ruleForm.username" clearable placeholder="输入账号" autocomplete="off" >
            <template #prefix>
              <el-icon class="el-input__icon"><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input  class="password" lang="en-hans" show-password v-model="ruleForm.password" type="password" placeholder="输入密码" autocomplete="off">
            <template #prefix>
              <el-icon class="el-input__icon"><Unlock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input lang="en-hans" v-model="ruleForm.email" clearable placeholder="输入邮箱" autocomplete="off" >
            <template #prefix>
              <el-icon class="el-input__icon"><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item class="username" prop="code">
          <el-col :span="16">
            <el-input lang="en-hans" v-model="ruleForm.code" placeholder="输入验证码" autocomplete="off" >
              <template #prefix>
                <el-icon class="el-input__icon"><EditPen /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="8">
            <el-button link :disabled="emailBtn" :loading="loadEmail" @click="getCode()" class="font-size" plain lang="en-hans">
              {{ codeText }}
            </el-button>
          </el-col>

        </el-form-item>
        <el-form-item class="to-login">
          <el-button :loading="loading" style="width: 100%" lang="en-hans" type="primary" @click="submitForm(ruleFormRef)">
            注   册
          </el-button>
        </el-form-item>
        <el-form-item class="to-login">
          <el-link href="/auth" type="primary">返回登录</el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import {ElForm, ElFormItem, ElInput, ElButton, ElMessage} from 'element-plus'
import {Unlock, User,Message,EditPen} from "@element-plus/icons-vue";
import router from "@/router";
import {getEmailCode, register} from "@/api/auth";
import {validEmail} from "@/utils/validUtil";


const ruleFormRef = ref(null)
/**
 * 账号校验
 * @param rule
 * @param value
 * @param callback
 */
const validateUsername = (rule, value, callback) => {
  value=value.trim()
  const regexp=/^[a-zA-Z0-9]{5,11}$/
  if (value === '') {
    callback(new Error('请输入账号'))
  } else if (!regexp.test(value)){
    callback(new Error('用户名必须为5-11位字母、数字组成'))
  }else{
    callback()
  }
}
/**
 * 密码校验
 * @param rule
 * @param value
 * @param callback
 */
const validatePassword = (rule, value, callback) => {
  value = value.trim()
  const regexp=/^[a-zA-Z0-9.@#]{6,20}$/
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (!regexp.test(value)) {
    callback(new Error('密码长度为6-20位字母、数字、符号(.@#)'))
  }else {
    callback()
  }
}
/**
 * 校验邮箱
 * @param rule
 * @param value
 * @param callback
 */
const validateEmail = (rule, value, callback) => {
  value = value.trim();
  // 校验是否为空
  if (value === '') {
    callback(new Error('请输入邮箱')); // 错误情况，返回错误信息
  }
  // 校验是否格式不正确
  else if (!validEmail(value)) {
    callback(new Error('邮箱格式不符')); // 错误情况，返回错误信息
  }
  else {
    callback(); // 这里 callback 不带参数表示校验通过
  }
};

/**
 * 校验邮箱
 * @param rule
 * @param value
 * @param callback
 */
const validateCode = (rule, value, callback) => {
  value=value.trim()
  const regexp=/^[0-9]{6}$/
  if (value === '') {
    callback(new Error('请输入验证码'))
  } else if (!regexp.test(value)) {
    callback(new Error('验证码需要6位数字'))
  }else {
    callback()
  }
}

const codeText = ref('获取验证码')

const ruleForm = reactive({
  username: '',
  password: '',
  email:'',
  code: '',
})

const rules = reactive({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  email: [{ validator: validateEmail, trigger: 'blur' }],
  code: [{ validator: validateCode, trigger: 'submit' }],
})

const loading= ref(false)

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (!valid) return;
    loading.value=true;
    register(ruleForm).then((res) => {
      ElMessage.success(res.message)
      //切换登录页
      router.push('/auth')
    }).catch(() => {
      loading.value = false;
    })
  })
}
const loadEmail= ref(false)
const emailBtn =ref(false)
const getCode = () => {
  // 手动触发邮箱校验
  ruleFormRef.value.validateField('email', (errorMessage) => {
    const value = ruleForm.email.trim();
    // 校验是否为空
    if (value === '') {
      return; // 错误情况，返回错误信息
    }
    // 校验是否格式不正确
    else if (!validEmail(value)) {
      return; // 错误情况，返回错误信息
    }
    // 邮箱校验通过，继续获取验证码
    let count = 60;
    loadEmail.value = true;
    emailBtn.value = true;
    codeText.value = '正在发送';
    getEmailCode({email:ruleForm.email}).then((res) => {
      loadEmail.value = false;
      ElMessage.success(res.message);
      const timer = setInterval(() => {
        count--;
        codeText.value = count + 's';
        if (count <= 0) {
          clearInterval(timer);
          emailBtn.value = false;
          codeText.value = '获取验证码';
        }
      }, 1000);
    }).catch(() => {
      loadEmail.value = false;
      emailBtn.value = false;
      codeText.value = '获取验证码';
    });
  });
};


</script>

<style>
.main-box{
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.login-box{
  display: flex;
  justify-content: center;
  align-items: center;
  width: 250px;
  height: 350px;
  border-radius: 10px;
  background: rgba(255,255,255,1);
  box-shadow: 0 0 15px darkgray;
  padding: 25px;
}
.login-title{
  width: 100%;
  margin: 15px 0 15px;
}
.username .el-input__inner{
  letter-spacing: 3px !important;
}
.password .el-input__inner{
  letter-spacing: 2px !important;
}
.el-form-item__content{
  justify-content: center;
  .el-link__inner{
    user-select: none;
    line-height: 24px;
    margin-top: 5px;
    font-size: 13px;
    letter-spacing: 3px !important;
  }
}
.to-login{
  margin-bottom: 5px !important;
}
.font-size{
  font-size: 10px;
  letter-spacing: 3px !important;
}
</style>